//
// Created by tview on 20-12-23.
//

typedef struct tag_IIR_State_2order{
    float y2;
    float y1;
    float x1;
    float x0;
} IIR_State_2order;

#define  ONE_FRAME_SAMPLE_SIZE   1024

void cy_signal_filter_by_iir(signed short* pcmIn, IIR_State_2order* filter_state, float a[], float b[], signed short* pcmOut)

{
    int i;
    float x2;
    float tmp;
    for ( i = 0; i < ONE_FRAME_SAMPLE_SIZE; i++ )

    {

        x2 = filter_state->x1;

        filter_state->x1 = filter_state->x0;

        filter_state->x0 = pcmIn[i];

        tmp = ( float )(b[0]* filter_state->x0 + b[1]* filter_state->x1 +

                        b[2] * x2 - a[1] * filter_state->y1 - a[2] * filter_state->y2);
        if(tmp >= 32767)
        {
            tmp = 32767;
        }
        if(tmp <= -32768)
        {
            tmp = -32768;
        }

        pcmOut[i] = (signed short)tmp;

        filter_state->y2 = filter_state->y1;

        filter_state->y1 = tmp;

    }

}